/**
 * Created by lijizhuang on 16/9/27.
 */
define(['jquery', 'underscore', 'backbone', 'bootstrap', 'text!modules/activities/publishView.html', 'extensions/stringExts',
        'plugins/jquery.citys'],
    function ($, _, Backbone, Bootstrap, PublishViewTemplate, StringExts) {
        var publishView = Backbone.View.extend({
            tagName: 'div',
            //className:'pubContents',
            template: _.template(PublishViewTemplate),

            initialize: function () {
                _publishView = this;
                ue = null;
                auto = null;
                placeSearch = null;
                mapShow = false;
                lnglatXY = null; //经纬度坐标
            },

            events: {
                "change #fromTimeSelect": "onFromTimeSelected",
                "change #toTimeSelect": "onToTimeSelected",
                'focusin input': 'onTextboxFocus',
                'focusin #address': 'onAddressTbFocus',
                'click .itemContent .locate': 'onLocatedClick',
                'click .addTag': 'onAddTagClick',
                'click .removeTag': 'onRemoveTagClick',
                'click #doPub': 'onPublishClick',
                'click #doSave': 'onSaveClick'
            },

            onPublishClick: function () {
                console.log('publish clicked');
            },

            onSaveClick: function () {
                //获取编辑器的内容
                console.log(ue.getContent());
            },

            onLocatedClick: function (e) {
                require(['amap'], function () {
                    if (!mapShow) {
                        mapShow = true;

                        this.$('#mapContainer').show();
                        AMap.service('AMap.PlaceSearch', function () {
                            var map = new AMap.Map("mapContainer", {
                                resizeEnable: false
                            });

                            placeSearch = new AMap.PlaceSearch({
                                map: map
                            });  //构造地点查询类

                            //var city = _publishView.$("select[name='city'] option:selected").text();
                            //placeSearch.setCity(city);
                            //
                            //var addr = _publishView.$("#address").val();
                            //if($.trim(addr).length > 0){
                            //    placeSearch.search(addr, function(status, result) {
                            //    });
                            //}
                            //else{
                            //    placeSearch.search(city, function(status, result) {
                            //    });
                            //}

                            _publishView.renderMap();
                        });

                    }
                    else {
                        mapShow = false;
                        this.$('#mapContainer').hide();
                    }
                });
            },

            renderMap: function () {
                var city = _publishView.$("select[name='city'] option:selected").text();
                placeSearch.setCity(city);

                var addr = _publishView.$("#address").val();
                if ($.trim(addr).length > 0) {
                    placeSearch.search(addr, function (status, result) {
                    });
                }
                else {
                    placeSearch.search(city, function (status, result) {
                    });
                }
            },

            setDefultProvinceAndCity: function () {
                require(['amap'], function () {
                    //AMap.plugin('AMap.Geolocation', function() {
                    //    geolocation = new AMap.Geolocation({
                    //        enableHighAccuracy: true,//是否使用高精度定位，默认:true
                    //        timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                    //        //buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    //        //zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    //        //buttonPosition:'RB'
                    //    });
                    //
                    //    geolocation.getCurrentPosition();
                    //    AMap.event.addListener(geolocation, 'complete', function (data) {
                    //        var lng = data.position.getLng();
                    //        var lat = data.position.getLat();
                    //
                    //        lnglatXY = [lng, lat];
                    //        if (lnglatXY == null || lnglatXY == undefined) {
                    //            return;
                    //        }
                    //        else {
                    //            var geocoder = new AMap.Geocoder({
                    //                radius: 1000,
                    //                extensions: "all"
                    //            });
                    //
                    //            geocoder.getAddress(lnglatXY, function(status, result) {
                    //                if (status === 'complete' && result.info === 'OK') {
                    //                    _publishView.geocoder_CallBack(result);
                    //                }
                    //            });
                    //        }
                    //    });
                    //
                    //    AMap.event.addListener(geolocation, 'error', function (data) {
                    //        console.log('定位失败: '+ data);
                    //    });
                    //});

                    if (navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(function (position) {
                            lnglatXY = [position.coords.longitude, position.coords.latitude];

                            if (lnglatXY == null || lnglatXY == undefined) {
                                return;
                            }
                            else {
                                var geocoder = new AMap.Geocoder({
                                    radius: 1000,
                                    extensions: "all"
                                });

                                geocoder.getAddress(lnglatXY, function(status, result) {
                                    if (status === 'complete' && result.info === 'OK') {
                                        _publishView.geocoder_CallBack(result);
                                    }
                                });
                            }
                        },
                            function (error) {
                                switch(error.code) {
                                    case error.PERMISSION_DENIED:
                                        console.log("定位失败, 用户拒绝开启定位");
                                        break;
                                    case error.POSITION_UNAVAILABLE:
                                        console.log("定位失败, 地理信息不存在");
                                        break;
                                    case error.TIMEOUT:
                                        console.log("定位失败, 请求超时");
                                        break;
                                    case error.UNKNOWN_ERROR:
                                        console.log("定位失败, 未知的异常");
                                        break;
                                }
                            }
                        );
                    }
                });



                //require(['amap'], function () {
                //    AMap.service(["AMap.CitySearch"], function () {
                //        //实例化城市查询类
                //        var citysearch = new AMap.CitySearch();
                //        //自动获取用户IP，返回当前城市
                //        citysearch.getLocalCity(function (status, result) {
                //            if (status === 'complete' && result.info === 'OK') {
                //                if (result && result.city && result.bounds) {
                //                    var cityinfo = result.city;
                //                    var citybounds = result.bounds;
                //                    targetCity = cityinfo;
                //                    console.log(result.bounds);
                //
                //                    //   toast("您当前所在城市：" + cityinfo + ",code:"+ cityinfo.replace("市",""));
                //                }
                //            } else {
                //                //toast("您当前所在城市：" + result.info + "");
                //            }
                //        });
                //    });
                //});
            },

            geocoder_CallBack:function(data){
                var dProvince = data.regeocode.addressComponent.province;
                var dCity = data.regeocode.addressComponent.city;
                var dDistrict = data.regeocode.addressComponent.district;

                if(dProvince.length > 0 && dCity.length == 0 && dDistrict.length > 0) {
                    $("select[name='province'] option").filter(function() {
                        return this.text == dProvince;
                    }).attr('selected', true);

                    //手动触发及联修改
                    $("select[name='province'] option").trigger("change");

                    $("select[name='city'] option").filter(function() {
                        return this.text == dDistrict;
                    }).attr('selected', true);
                }

            },

            onAddTagClick: function (e) {
                //最多允许添加5个标签
                if (this.$('.tagUnit').length < 5) {
                    var ele = "<div class=\"tagUnit\"><div><input type=\"text\" class=\"tagInput\" name=\"tagInputTB\" id=\"tagInputTB\"></div> <div class=\"removeTag\"></div> </div>";
                    $(ele).insertBefore($(e.currentTarget));
                }
            },

            onRemoveTagClick: function (e) {
                $(e.currentTarget).parent().remove();
            },

            onTextboxFocus: function (e) {
                $(e.currentTarget).tooltip('hide');
                _publishView.clearError($(e.currentTarget));
            },

            onAddressTbFocus: function () {
                require(['amap'], function () {

                    //AMap.plugin('AMap.Autocomplete',function(){//回调函数
                    //    //实例化Autocomplete
                    //    var autoOptions = {
                    //        city: "", //城市，默认全国
                    //        input:"input_id"//使用联想输入的input的id
                    //    };
                    //    autocomplete= new AMap.Autocomplete(autoOptions);
                    //    //TODO: 使用autocomplete对象调用相关功能
                    //});

                    //输入提示
                    var city = _publishView.$("select[name='city'] option:selected").text();
                    AMap.plugin('AMap.Autocomplete', function () {
                        var autoOptions = {
                            city: city,
                            input: "address"
                        };
                        auto = new AMap.Autocomplete(autoOptions);

                    });

                    AMap.service('AMap.PlaceSearch', function () {
                        var map = new AMap.Map("mapContainer", {
                            resizeEnable: false
                        });

                        placeSearch = new AMap.PlaceSearch({
                            map: map
                        });  //构造地点查询类

                        _publishView.renderMap();

                        AMap.event.addListener(auto, "select", function (e) {
                            placeSearch.setCity(e.poi.adcode);
                            placeSearch.search(e.poi.name);  //关键字查询
                        });//注册监听，当选中某条记录时会触发

                    });
                });
            },

            showError: function (target, wording, place) {
                if (!target.hasClass('validate-failed')) {
                    target.addClass('validate-failed');
                }

                place = (place === undefined || place.length === 0) ? 'top' : place; //默认为top

                target.tooltip({'trigger': 'manual', 'title': wording, 'placement': place});
                target.tooltip('show');
            },

            clearError: function (target) {
                if (target.hasClass('validate-failed')) {
                    target.removeClass('validate-failed');
                }

                target.tooltip('hide');
            },

            onFromTimeSelected: function (e) {
                //如果两者是同一天的不同时间,那么必须保证起始时间不大于结束时间
                if (_publishView.$("#fromDateTB").val() === _publishView.$("#toDateTB").val() &&
                    $(e.currentTarget).val() > _publishView.$('#toTimeSelect').val()) {

                    _publishView.$('#toTimeSelect').val($(e.currentTarget).val());
                }
            },

            onToTimeSelected: function (e) {
                //如果两者是同一天的不同时间,那么必须保证起始时间不大于结束时间
                if (_publishView.$("#fromDateTB").val() === _publishView.$("#toDateTB").val() &&
                    $(e.currentTarget).val() < _publishView.$('#fromTimeSelect').val()) {

                    $(e.currentTarget).val(_publishView.$('#fromTimeSelect').val());
                }
            },

            zeroFill: function (number, width) {
                width -= number.toString().length;
                if (width > 0) {
                    return new Array(width + (/\./.test(number) ? 2 : 1)).join('0') + number;
                }
                return number + "";
            },

            render: function () {
                this.$el.html(this.template());
                this.afterRender();

                return this;
            },

            afterRender: function () {
                this.setDefultProvinceAndCity();

                //设置省市下拉列表及初始化
                this.$('.itemContent').citys({province: '江苏省', city: '苏州市'});

                //设置时间HH:ss
                var selection = "";

                for (var i = 0; i < 24; i++) {
                    selection += "<option value='" + this.zeroFill(i, 2) + "00'>" + this.zeroFill(i, 2) + ":00" + "</option>";
                    selection += "<option value='" + this.zeroFill(i, 2) + "30'>" + this.zeroFill(i, 2) + ":30" + "</option>";
                }
                this.$("#fromTimeSelect").html(selection);
                this.$("#toTimeSelect").html(selection);
                this.$("#fromTimeSelect option").filter(function () {
                    return $(this).text() == '08:00';
                }).prop('selected', true);

                this.$("#toTimeSelect option").filter(function () {
                    return $(this).text() == '09:00';
                }).prop('selected', true);

                //设置UEditor
                require(['baidueditor', 'zeroclipboard', 'bdlanglang'], function (UE, zcl, bdlanglang) {

                    window.ZeroClipboard = zcl;
                    ue = UE.getEditor('u_editor', {
                        //关闭字数统计
                        wordCount: false,
                        //关闭elementPath
                        elementPathEnabled: false,
                        initialFrameHeight: 350,
                        initialFrameWidth: 803,
                        //默认会将外部进入的html数据中的Div标签转换成P标签
                        allowDivTransToP: false,
                        //自动排版参数
                        autotypeset: {
                            mergeEmptyline: false,
                            removeEmptyline: false
                        }
                    });
                });

                this.$('select[name="province"], select[name="city"]').bind('click', function (e) {
                    if (mapShow) {
                        mapShow = false;
                        _publishView.$('#mapContainer').hide();
                    }
                });

            }
        });

        return publishView;
    });